package org.yunfeng.manage.common.util;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
/**
 * fastjson工具类
 * TODO 暂时版本, 碍于渣渣的官方文档, 有待更新
 */
public class JsonUtils {
	private JsonUtils() {}
	
	private static final SerializeConfig config;
	private static final String dateFormat;
	private static final SerializerFeature[] features = {
//		SerializerFeature.UseSingleQuotes,	// 字符串使用单引号
		SerializerFeature.WriteMapNullValue, // 输出空置字段
		SerializerFeature.WriteNullListAsEmpty, // list字段如果为null，输出为[]，而不是null
		SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null，输出为""，而不是null
		
	};
	
	static {
		config = new SerializeConfig();
//		config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
//		config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
		dateFormat = "yyyy-MM-dd HH:mm:ss";
		config.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
	}

	public static String toJson(Object object) {
		return JSON.toJSONString(object, config, features);
	}

	public static String toJsonNoFeatures(Object object) {
		return JSON.toJSONString(object, config);
	}

	public static <T> T fromJson(String text, Class<T> clazz) {
		return JSON.parseObject(text, clazz);
	}

	public static <T> List<T> toList(String text, Class<T> clazz) {
		return JSON.parseArray(text, clazz);
	}

	public static Map<String, Object> JsonToMap(String s) {
		Map<String, Object> m = JSONObject.parseObject(s);
		return m;
	}

	public static String mapToJson(Map<String, Object> m) {
		String s = JSONObject.toJSONString(m);
		return s;
	}
	
}
